package bintree.LeetCode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
//非递归写后续遍历——借用栈
public class Num145_postorder_非递归 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null){
            return ret;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        TreeNode prev = null;//判断右子树是否走完

        while(cur != null || !stack.isEmpty()){

            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();

            if(cur.right == null || cur.right == prev){
                //说明右子树处理完毕，可以放心的访问了
                ret.add(cur.val);
                prev = cur;//那么此时的cur就是最新处理完毕的节点
                cur = null;//要把处理后的cur重新置空，不然会死循环
            }else{
                //说明此时右子树还没有处理完毕，需要把节点重新压入栈
                stack.push(cur);
                cur = cur.right;
            }

        }
        return ret;
    }
}
